<!-- 设备IDC -->
<template>
  <basic-container>
    <avue-crud
      v-model="form"
      ref="crud"
      :option="option"
      :table-loading="loading"
      :defaults.sync="defaults"
      :data="data"
      :page.sync="page"
      :permission="permissionList"
      :before-open="beforeOpen"
      :before-close="beforeClose"
      @row-save="rowSave"
      @row-update="addUpdate"
      @row-del="rowDel"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
    >
      <!-- 删除 -->
      <template slot="menuLeft">
        <el-button type="danger" size="small" icon="el-icon-delete" plain v-if="permission.equipmentidc_delete" @click="handleDelete">删 除</el-button>
      </template>
      <!--      <template slot="menuRight">-->
      <!--        <user-table-config :option="option" @confirm="(val) => handleSetUserConfig(val, pageCode)"></user-table-config>-->
      <!--      </template>-->
      <template slot-scope="{ row }" slot="histroyIDC">
        <span class="idc-record-text" @click="openDispatchProductionLineModal(row.id)">记录</span>
      </template>
    </avue-crud>
    <!-- 弹框 -->
    <common-modal-template ref="commonModalTemplate" :option="tableOption" @getSelectedRows="getSelectedRows" :key="timer" @newKey="newKey"></common-modal-template>
  </basic-container>
</template>

<script>
import { getList, getDetail, remove, add, update } from '@/api/product/equipmentidc';
import CommonModalTemplate from '@/components/common-modal-template/common-modal-template.vue';
import { mapGetters } from 'vuex';
import userTableConfig from '@/components/user-table-config/index.vue';
import userConfig from '@/mixins/userConfig';
export default {
  components: {
    CommonModalTemplate,
    userTableConfig
  },
  mixins: [userConfig()],
  data() {
    return {
      pageCode: 'EQUITPMENT_TIDC',
      form: {},
      query: {},
      defaults: {},
      loading: true,
      data: [],
      commonDialog: {
        dispatch: true
      },
      tableOption: {}, //公用模态框配置信息
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      selectionList: [],
      option: {
        height: 'calc(100vh - 440px)',
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchMenuSpan: 5,
        border: true,
        index: true,
        indexLabel: '序号',
        addBtn: true,
        // cellBtn: true,
        viewBtn: false,
        editBtn: true,
        delBtn: true,
        selection: true,
        dialogClickModal: false,
        menu: true,
        labelWidth: 120,
        columnBtn: false,
        // menuWidth: 120,
        column: [
          {
            label: '产品编码',
            prop: 'productCode',
            search: true,
            searchType: 'input',
            type: 'search',
            disabled: true,
            rules: [
              {
                required: true,
                message: '请输入产品编码'
              }
            ],
            order: 1,
            appendClick: () => {
              this.openUserCommonModal({ type: 'productCode' });
            }
          },
          {
            label: '产品名称',
            prop: 'productName',
            order: 2,
            disabled: true,
            rules: [
              {
                required: true,
                message: '请输入产品名称'
              }
            ]
          },
          {
            label: '设备型号',
            prop: 'equipmentModel',
            order: 3,
            search: true,
            searchType: 'input',
            type: 'search',
            disabled: true,
            rules: [
              {
                required: true,
                message: '请输入设备型号'
              }
            ],
            appendClick: () => {
              this.openUserCommonModal({ type: 'equipmentModel' });
            }
          },
          {
            label: 'IDC历史',
            prop: 'histroyIDC',
            slot: true
          },
          {
            label: 'IDC（Min）',
            prop: 'idc',
            type: 'number',
            minRows: 0,
            labelTip: 'IDC（Ideal Cycle Time）是指标准产品理论所需工时，或理论节拍（单位：分钟）',
            rules: [
              {
                required: true,
                message: '请输入IDC（Min）'
              }
            ]
          },
          {
            label: '制定人',
            prop: 'makerName',
            disabled: true
          },
          {
            label: '制定日期',
            prop: 'createTime',
            type: 'datetime',
            disabled: true,
            format: 'yyyy-MM-dd HH:mm:ss',
            valueFormat: 'yyyy-MM-dd HH:mm:ss'
          }
        ]
      },
      modalName: '', //打开公用模态框名称
      tableOption: {}, //公用模态框配置信息
      timer: new Date().getTime() //不同内容使用同一个模态框结构，key值不同需要重新请求渲染数据，否则会请求到上一个使用的数据内容
    };
  },
  mounted() {
    this.$nextTick(() => {
      this.$structuralSplit();
    });
  },
  computed: {
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(',');
    },
    ...mapGetters(['permission']),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.equipmentidc_add, false),
        viewBtn: this.vaildData(this.permission.equipmentidc_view, false),
        delBtn: this.vaildData(this.permission.equipmentidc_delete, false),
        editBtn: this.vaildData(this.permission.equipmentidc_edit, false)
      };
    }
  },

  methods: {
    rowSave(row, done, loading) {
      add([row]).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          done();
        },
        (error) => {
          loading();
          window.console.log(error);
        }
      );
    },
    addUpdate(row, index, done, loading) {
      add([row]).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          done();
        },
        (error) => {
          loading();
          window.console.log(error);
        }
      );
    },
    rowDel(row) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
        });
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          this.$refs.crud.toggleSelection();
        });
    },
    beforeOpen(done, type) {
      if (['add', 'edit', 'view'].includes(type)) {
        this.defaults.histroyIDC.display = false;
      }
      done();
    },
    beforeClose(done, type) {
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },

    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then((res) => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    },
    // IDC记录 弹框 配置
    openDispatchProductionLineModal(id) {
      this.modalName = 'dispatchProductionLineModal';
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '记录',
        url: '/api/mes-product/ems-equipment-idc/list-of-change',
        query: {
          id: id
        },
        page: true,
        // isPage: false,
        rowSelectionType: 'single',
        menu: false,
        editBtn: false,
        columnDefs: [
          {
            label: '更新前IDC',
            prop: 'idcBefore'
          },
          {
            label: '修改人',
            prop: 'changeBy	'
          },
          {
            label: '更新后IDC',
            prop: 'idcAfter'
          },
          {
            label: '更新时间',
            prop: 'updateTime'
          }
        ]
      };
    },

    openUserCommonModal(params) {
      let { type } = params;
      switch (type) {
        // 产品编码
        case 'productCode':
          this.openProductModal();
          break;
        // 设备型号
        case 'equipmentModel':
          this.openEquipmentModal();
          break;
        default:
          break;
      }
    },
    // 产品编码 弹框 配置
    openProductModal() {
      this.modalName = 'partmasterModal';
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择物料信息（双击进行选择）',
        url: '/api/mes-admin/part-master/page',
        isPage: true,
        query: {
          semifinished: true
        },
        rowSelectionType: 'single',
        menu: false,
        editBtn: false,
        menuWidth: 100,
        columnDefs: [
          {
            label: '类别',
            prop: 'categoryId',
            search: true,
            type: 'tree',
            dicUrl: '/api/mes-admin/part-category/tree',
            props: {
              label: 'title',
              value: 'id'
            }
          },
          {
            label: '编码',
            prop: 'partNo',
            search: true
          },
          {
            label: '名称',
            prop: 'name',
            search: true
          },
          {
            label: '型号',
            prop: 'partModel'
          },
          {
            label: '描述',
            prop: 'description'
          },
          {
            label: '版本',
            prop: 'revision'
          },
          {
            label: '仓库物料类别',
            prop: 'partType',
            props: {
              label: 'dictValue',
              value: 'dictKey'
            },
            dicUrl: '/api/blade-system/dict/dictionary?code=part_type'
          }
        ]
      };
    },
    // 设备型号 弹框 配置
    openEquipmentModal() {
      this.modalName = 'equipmentModal';
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择设备信息（双击进行选择）',
        url: '/api/mes-product/ems-equipment/page?type=PRINTER',
        rowSelectionType: 'single',
        page: true,
        menu: false,
        editBtn: false,
        menuWidth: 100,
        columnDefs: [
          {
            label: '型号',
            prop: 'model'
          },
          {
            label: '类型',
            // 设备类型：打印机PRINTER, 工具TOOL，辅料：AUXILIARY, 机器设备：MACHINE
            prop: 'equipmentType',
            search: true,
            type: 'select',
            dicUrl: '/api/blade-system/dict/dictionary?code=equipment_type',
            cascader: ['subType'], //级联属性
            props: {
              label: 'dictValue',
              value: 'dictKey'
            },
            rules: [
              {
                required: true,
                message: '请选择类型',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '子类型',
            // 子类型：飞达/钢网/刮刀/锡膏
            prop: 'subType',
            type: 'select',
            dicFlag: false,
            dicUrl: '/api/blade-system/dict/dictionary?code={{key}}',
            props: {
              label: 'dictValue',
              value: 'dictKey'
            },
            rules: [
              {
                required: false,
                message: '请选择子类型',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '编码',
            prop: 'code',
            search: true,
            rules: [
              {
                required: true,
                message: '请输入编码',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '名称',
            prop: 'name',
            search: true,
            rules: [
              {
                required: true,
                message: '请输入名称',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '负责人',
            prop: 'principalName',
            type: 'search',
            disabled: true,
            placeholder: '请选择 负责人',
            rules: [
              {
                required: false,
                message: '请选择负责人',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '联系方式',
            prop: 'contacts',
            hide: true,
            rules: [
              {
                required: false,
                message: '请输入联系方式',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '长',
            prop: 'length',
            type: 'number',
            precision: 2,
            minRows: 1,
            hide: true,
            rules: [
              {
                required: false,
                message: '请输入长',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '宽',
            prop: 'width',
            type: 'number',
            precision: 2,
            minRows: 1,
            hide: true,
            rules: [
              {
                required: false,
                message: '请输入宽',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '高',
            prop: 'height',
            type: 'number',
            precision: 2,
            minRows: 1,
            hide: true,
            rules: [
              {
                required: false,
                message: '请输入高',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '规格描述',
            prop: 'specification',
            hide: true,
            rules: [
              {
                required: false,
                message: '请输入规格描述',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '可用数量',
            prop: 'quantityAvailable',
            type: 'number',
            precision: 0,
            minRows: 1,
            hide: true,
            rules: [
              {
                required: false,
                message: '请输入可用数量',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '在用数量',
            prop: 'quantityReserved',
            type: 'number',
            precision: 0,
            minRows: 1,
            hide: true,
            rules: [
              {
                required: false,
                message: '请输入在用数量',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '单位',
            prop: 'uom',
            hide: true,
            rules: [
              {
                required: false,
                message: '请输入单位',
                trigger: 'blur'
              }
            ]
          }
        ]
      };
    },
    // 获取选择的物料模态框行数据
    getSelectedRows(rowData) {
      switch (this.modalName) {
        // IDC记录
        case 'dispatchProductionLineModal':
          break;
        // 产品编码
        case 'partmasterModal':
          this.form.productCode = this._get(rowData, 'partNo', '');
          this.form.productName = this._get(rowData, 'name', '');
          this.form.productId = this._get(rowData, 'id', '');
          break;
        // 设备型号
        case 'equipmentModal':
          this.form.equipmentModel = this._get(rowData, 'model', '');
        default:
          break;
      }
    },
    // 重新加载公用表格弹窗组件
    newKey() {
      this.timer = new Date().getTime();
    }
  }
};
</script>

<style lang="scss" scoped>
.idc-record-text {
  color: #409eff;
  cursor: pointer;
}
</style>
